<?php

namespace App\Services;

use Exception;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;
use TencentCloud\Common\CommonClient;
use TencentCloud\Common\Credential;

class TTSService
{
    /**
     * @throws \TencentCloud\Common\Exception\TencentCloudSDKException
     * @throws Exception
     */
    static public function textToAudio($text): string
    {
        $cred = new Credential(config("app.qcloud_secret_id"), config("app.qcloud_secret_key"));
        $client =  new CommonClient("tts", "2019-08-23", $cred, "ap-guangzhou");
        $body = [
            'Text' => $text,
            'ModelType' => 1,
        ];
        $resp = $client->callJson("CreateTtsTask", $body);
        // Log::info(json_encode($resp));
        $taskId = Arr::get($resp, "Data.TaskId", 0);
        if (!$taskId) {
            Log::error("文字转音频CreateTtsTask失败");
            throw new Exception("文字转音频CreateTtsTask失败");
        }
        Log::info($taskId);
        for($i = 0 ; $i < 8; $i++) {
            sleep(1);
            $body = ['TaskId' => $taskId];
            $resp = $client->callJson("DescribeTtsTaskStatus", $body);
            // Log::info(json_encode($resp));
            $status = Arr::get($resp, "Data.Status", 0);
            if ($status == 2) {
                $resultUrl = Arr::get($resp, 'Data.ResultUrl', '');
                Log::info($resultUrl);
                return trim($resultUrl);
            }
        }
        Log::error("文字转音频DescribeTtsTaskStatus多次失败");
        throw new Exception("文字转音频DescribeTtsTaskStatus多次失败");
    }
}
